package com.woniuxy.permission.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.zsd.commons.core.exception.ZsdException;
import com.woniuxy.permission.entity.Resource;
import com.woniuxy.permission.entity.RoleResource;
import com.woniuxy.permission.form.AddResourceForm;
import com.woniuxy.permission.mapper.ResourceMapper;
import com.woniuxy.permission.mapper.RoleResourceMapper;
import com.woniuxy.permission.service.IResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-13
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements IResourceService {
   @javax.annotation.Resource
    private ResourceMapper resourceMapper;
   @javax.annotation.Resource
   private RoleResourceMapper roleResourceMapper;



    @Override
    public void addResource(AddResourceForm form) throws Exception {
        //判断数据库里是否有相同的名称
        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", form.getName());
        Long count = this.count(queryWrapper);
        if (count > 0) {
            throw new ZsdException("资源名称已存在，请勿重复添加", 500);
        }
        Resource resource = new Resource();
        resource.setName(form.getName());
        resource.setResource(form.getDescription());
        //添加资源
        this.save(resource);


    }

    @Override
    public Object getAllResources() throws Exception {
        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>();
        return resourceMapper.selectList(queryWrapper);
    }

    @Override
    public void deleteResource(Integer resourceId) throws Exception {
        // 查询该资源是否被角色关联在role_resource表
        QueryWrapper<RoleResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", resourceId);
        Long count = roleResourceMapper.selectCount(queryWrapper);
        if (count > 0) {
            // 如果资源被关联，则抛出异常
            throw new ZsdException("该资源被角色关联，请先解除关联关系", 500);
        }

        // 如果没有被关联，删除资源
        this.removeById(resourceId);
    }


}
